<template>
  <div id="add-blog" class="container">
      <div class="well">
        <h2 id="title">添加博客</h2>
        <div v-if="error" class="alert alert-danger alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <strong>Warning!</strong> {{error}}
        </div>
        <form action="" v-if="!submitBlog">
            <label >博客标题:</label>
            <input class="form-control" type="text" v-model="blog.title" required>
            <label for="">博客内容:</label>
            <textarea class="form-control" v-model="blog.content" cols="30" rows="10"></textarea>
            <div id="checkboxes" class="checkbox">
                <label v-for="cate in cates">
                     <input type="checkbox" v-bind:value="cate.id" v-model="checkedCatesId">{{cate.name}}
                </label>
            </div>
            <button v-on:click='blogSubmit' class="btn btn-default">提交</button>
        </form>
        <div v-if="submitBlog">
          <h1>博客提交成功</h1>
          <router-link to="/" class="btn btn-default">查看博客</router-link>
          <button class="btn btn-info" v-on:click="writeBlog">继续写博客</button>
        </div>
        
      </div>
  </div>
</template>

<script>
export default {
  name: "add-blog",
  data() {
    return {
      cates: [],
      blog: {},
      checkedCatesId: [],
      submitBlog: false,
      error:""
    };
  },
  methods: {
    blogSubmit(e) {
      e.preventDefault();
      console.log(this.blog);
      this.blog.cates = [];
      for (let cateId of this.checkedCatesId) {
        this.blog.cates.push({
          id: cateId
        });
      }
      if(!this.blog.title){
        this.error = "请输入标题";
      }else if(!this.blog.content){
        this.error = "请输入内容";
      }else if(!this.blog.cates.length){
        this.error = "请选择至少一个类别";
      }else{
        this.$http
          .post("http://127.0.0.1:8000/myblog/api/add", this.blog)
          .then(response => {
            this.submitBlog = true;
            this.blog = {};
            this.checkedCatesId = [];
            this.error = "";
          });
       }
    },
    writeBlog() {
      this.submitBlog = false;
    }
  },
  created() {
    this.$http.get("http://127.0.0.1:8000/myblog/api/cates").then(response => {
      this.cates = response.body;
      console.log(this.cates);
    });
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
